#!/bin/bash

download_page ()
{
    rm -f $2
    let times=0

    while [ ! -s $2 ]
    do
        let times++
        if (( $times == 2 ))
        then
          echo "Site com problemas"
        fi

        links -source "$1" | iconv -f ISO_8859-1 -t UTF-8 | ./bandex.py > $2
        sleep 600
    done

    if (( $times != 1 ))
    then
      echo "Site de volta!"
    fi
}

site="http://www.prefeitura.unicamp.br/servicos.php?servID=119"
fold="bandex.page.old"
fnew="bandex.page.new"
email_list="bandex.email_list.txt"

download_page $site $fold
while ((1))
do
    hora=`date +%H%M | sed -e s/0*//`
    if [ -z $hora ]  # meia-noite
    then
        hora="0"
    fi

    if (($hora > 1900 || $hora < 830))
    then
        let wait_h=(8 - `date +%-H` + 24)%24
        let wait_m=(30 - `date +%-M` + 60)%60+$wait_h*60
        let wait_s=$wait_m*60
        echo "Poxa, tá tarde! Vou dormir $wait_m minutos..."
        sleep $wait_s
        echo "Acordei! Agora são:"
        date +%H:%M:%S
        echo
        continue
    fi

    download_page $site $fnew
    if ( ! diff -q -I '/' $fold $fnew )  # ignora alteração na data
    then
	cp $fnew $fold
	echo "Opa, cardápio novo!"

	./sms.py "`cat $fnew`" `cat $email_list`
        echo
    fi
done
